﻿using System;
using System.Management.Automation;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using PsTFS.Methodes;

namespace PsTFS.Objects
{
    /// <summary>
    /// Context applicatif
    /// </summary>
    public class Context
    {
        private Context() { }

        private void Reset()
        {
            _workItemStore = null;
            _workspace = null;
            _tfs = null;
        }

        /// <summary>
        /// Commande Powershell en cours d'execution
        /// </summary>
        public Cmdlet Cmdlet { get; set; }

        /// <summary>
        /// Serveur TFS en cours d'utilisation
        /// </summary>
        private TfsTeamProjectCollection _tfs;
        /// <summary>
        /// Serveur TSF
        /// </summary>
        public TfsTeamProjectCollection TFS
        {
            get
            {
                if (_tfs == null)
                {
                    throw new PsTFSException {ObjectError = "TFS"};
                }
                return _tfs;
            }
            set
            {
                Reset();
                _tfs = value;
            }
        }

        /// <summary>
        /// Projet en cour
        /// </summary>
        public TeamProject Project { get; private set; }

        internal void SetProject(string projectName)
        {
            Project = Methode.GetProject(projectName);
        }

        /// <summary>
        /// Utilisateur actuellement connexté
        /// </summary>
        public string User { get; set; }

        /// <summary>
        /// Workspace utilisé dans le cas d'un répertoire mappé
        /// </summary>
        private Workspace _workspace;

        /// <summary>
        /// Workspace utilisé dans le cas d'un répertoire mappé
        /// </summary>
        public Workspace Workspace
        {
            get
            {
                if (_workspace == null)
                {
                    // Tro to get the workspace 
                    try
                    {
                        // If there is only 1 local workspace, use it
                        var workspaces = Methode.GetAllWorkspaces(true);
                        if (workspaces.Count == 1)
                        {
                            _workspace = workspaces[0];
                        }
                        else
                        {
                            // Try to get it based on machinename and user.
                            _workspace = MethodService.VersionControlServer()
                                                      .GetWorkspace(Environment.MachineName, User);
                        }
                    }
                    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                }
                return _workspace;
            }
            set { _workspace = value; }
        }

        private WorkItemStore _workItemStore;
        public WorkItemStore WorkItemStore
        {
            get
            {
                if (_workItemStore != null)
                {
                    if (_workItemStore.TeamProjectCollection.Name != TFS.Name)
                    {
                        _workItemStore = null;
                    }
                }

                return _workItemStore ?? (_workItemStore = TFS.GetService<WorkItemStore>());
            }
        }

        #region Singleton implementation
        /// <summary>
        /// Variable privé pour le singleton
        /// </summary>
        private static Context _instance;

        /// <summary>
        /// Récupération du context
        /// </summary>
        /// <value>Retourne le context actuel</value>
        public static Context Instance
        {
            get { return _instance ?? (_instance = new Context()); }
        }

        public static void Initialize(string tfsAddress)
        {
            Instance.TFS = new TfsTeamProjectCollection(new Uri(tfsAddress));
            Instance.TFS.EnsureAuthenticated();
        }

        /// <summary>
        /// Vide le context
        /// </summary>
        public static void ClearContext()
        {
            _instance = null;
        }
        #endregion

		/// <summary>
		/// Service pour la gestion des Build
		/// </summary>
		/// <returns></returns>
		public IBuildServer BuildServer
		{
			get { return TFS.GetService<IBuildServer>(); }
		}
	}
}
